package com.live.shop.service;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

import androidx.annotation.NonNull;

import com.live.shop.ActivityCollector;
import com.live.shop.LoginActivity;
import com.live.shop.model.UserModel;
import com.live.shop.sql.UserDatabase;
import com.live.shop.tool.GetUtil;
import com.live.shop.tool.OkHttpUtils;

import org.json.JSONObject;

import java.io.IOException;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;
import okhttp3.Response;

public class TokenService extends Service {
    public TokenService() {
    }
    UserDatabase userDb;
    UserModel userModel;
    int tokenStartId;
    Timer timer;
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        tokenStartId = startId;
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        userDb = new UserDatabase(getApplicationContext());
        userModel = userDb.select();
        timer = new Timer();
        Date now = new Date();
        // 0立即执行一次任务
        timer.schedule(new Task(), new Date());
        // 3分钟后执行一次任务
        timer.schedule(new Task(), new Date(now.getTime() + 3 * 60 * 1000));
        // 5分钟后执行一次任务
        timer.schedule(new Task(), new Date(now.getTime() + 5 * 60 * 1000));
        // 10分钟后执行一次任务
        timer.schedule(new Task(), new Date(now.getTime() + 10 * 60 * 1000));
        // 20分钟后执行一次任务
        timer.schedule(new Task(), new Date(now.getTime() + 20 * 60 * 1000));
        // 30分钟后执行一次任务
        timer.schedule(new Task(), new Date(now.getTime() + 30 * 60 * 1000));
        // 每隔1小时执行一次任务
        timer.schedule(new Task(), new Date(now.getTime() + 60 * 60 * 1000),  60 * 60 * 1000);
    }
    class Task extends TimerTask {
        public void run() {
            Message message = new Message();
            message.what = 1;
            handler.sendMessage(message);
        }
    }
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    if(userModel.getToken() == null){
                        sendBroadcastMessage(0);
                    }else{
                        getAccount(GetUtil.checkUserInfo(),userModel.getToken());
                    }
                    break;
                case 2:
                    try {
                        JSONObject json = new JSONObject(msg.obj.toString());
                        sendBroadcastMessage(json.getInt("code"));
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                    break;
                case 3:
                    break;
            }
        }
    };
    public void getAccount(String url,String token){
        OkHttpUtils.sendOkHttpJsonTokenRequest(url, "",new okhttp3.Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Message message = new Message();
                message.what = 3;
                message.obj = "【请求异常】请联系管理员";
                handler.sendMessage(message);
            }
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String responseData = response.body().string();
                Message message = new Message();
                message.what = 2;
                message.obj = responseData;
                handler.sendMessage(message);
            }
        },token);
    }
    public void sendBroadcastMessage(int code) {
        if(code != 1){
            userDb.clearToken(code);
            Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            ActivityCollector.finishAll();
            stopSelf(tokenStartId);
        }
    }
    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        timer.cancel();
        boolean iswork = GetUtil.isServiceWork(getApplicationContext(),getPackageName()+".service.SuspendedWindowService");
        if(iswork) stopService(new Intent(getApplicationContext(), SuspendedWindowService.class));
    }
}